package sharedb

import (
	"errors"
	"fmt"
	"strings"
	"time"

	"gorm.io/gorm"
)

const (
	ServerTypeGate   = 2
	ServerTypeLogic  = 3
	ServerTypeBattle = 4
)

type Config_server struct {
	Id      int16      `gorm:"column:id"`
	Name    *string    `gorm:"column:name"`
	Type    int8       `gorm:"column:type"`
	Status  int8       `gorm:"column:status"`
	Ip      *string    `gorm:"column:ip"`
	IpLan   *string    `gorm:"column:ip_lan"`
	Port    int32      `gorm:"column:port"`
	Stock   int32      `gorm:"column:stock"`
	Created *time.Time `gorm:"column:created"`

	LogLevel string `gorm:"column:log_level"` // 日志级别
	HttpPort int32  `gorm:"column:http_port"` // http服务端口
	DevEnv   bool   `gorm:"column:dev_env"`   // 是否为开发环境
	LogSql   bool   `gorm:"column:log_sql"`   // 是否记录sql日志
}

func (tmp *Config_server) TableName() string {
	return "config_server"
}

func (tmp *Config_server) GetOneByModel(Conn *gorm.DB) error {
	result := Conn.Model(tmp).First(&tmp)
	if result.Error != nil {
		return result.Error
	}
	return nil
}

func (tmp *Config_server) GetAllWithOutGate(Conn *gorm.DB) ([]*Config_server, error) {
	var data []*Config_server
	result := Conn.Where("`type` != ? and `status` = ?", ServerTypeGate, 1).Find(&data)
	return data, result.Error
}

func (tmp *Config_server) Update_stock(Conn *gorm.DB, server_id int16, stock int32) bool {
	fields := make(map[string]interface{}, 1)
	fields["stock"] = stock
	if Conn.Model(tmp).Where("id = ?", server_id).Updates(fields).Error != nil {
		return false
	}
	return true
}

func (tmp *Config_server) Update_server_status(Conn *gorm.DB, server_id int16, status int8) bool {
	fields := make(map[string]interface{}, 1)
	fields["status"] = status
	if Conn.Model(tmp).Where("id = ?", server_id).Updates(fields).Error != nil {
		return false
	}
	return true
}

func (tmp *Config_server) GetAllOnlineFightServer(conn *gorm.DB) ([]*Config_server, error) {
	var data []*Config_server
	result := conn.Where("`type` = ? and `status` = ?", ServerTypeBattle, 1).Find(&data)
	return data, result.Error
}

func (tmp *Config_server) GetSidByAddr(conn *gorm.DB, addr string) (int32, error) {
	var data = strings.Split(addr, ":")
	if len(data) != 2 {
		return 0, errors.New(fmt.Sprintf("Get sid By addr error, addr:%s", addr))
	}
	var sid int32
	result := conn.Table(tmp.TableName()).Select("Id").Where("`ip_lan` = ? and type = ?", data[0], ServerTypeGate).Find(&sid)
	return sid, result.Error
}
